// 提交链接 https://leetcode.cn/problems/fruit-into-baskets/submissions/547479089/
// 904. 水果成篮
// 完成日期： 2024.8.30
// c++ 使用双指针与哈希表操作


class Solution {
public:
    unordered_map<int, int> ma;
    int totalFruit(vector<int>& fruits) {
        int ans = 0;
        int l = 0, r = 0;
        int n1 = -1, n2 = -1;
        while (r < fruits.size())
        {
            if (fruits[r] != n1 && fruits[r] != n2)
            {
                if (n1 == -1)
                {
                    n1 = fruits[r];
                    ma[n1] = r;
                }
                else
                {
                    if (n2 == -1)
                    {
                        n2 = fruits[r];
                        ma[n2] = r;
                    }
                    else
                    {
                        ans = max(ans, r - l);
                        l = min(ma[n1], ma[n2]) + 1;
                        if (ma[n1] < ma[n2])
                        {
                            n1 = fruits[r];
                            ma[n1] = r;
                        }
                        else
                        {
                            n2 = fruits[r];
                            ma[n2] = r;
                        }
                    }
                }
            }
            else
            {
                ma[fruits[r]] = r;
            }
            r += 1;
        }
        ans = max(ans, r - l);
        return ans;
    }
};